package floappcontest.core.backbeans;

import java.util.ArrayList;
import java.util.List;

import org.apache.myfaces.custom.fileupload.UploadedFile;

import floappcontest.core.beans.FloappFile;
import floappcontest.core.control.Control;
import floappcontest.core.dao.factory.HibernateDAOFactory;
import floappcontest.core.exception.FloAppException;

public class FileBean {

	private static final String FAILED = "FAILED"; //$NON-NLS-1$

	private static final String OK = "OK"; //$NON-NLS-1$
	
	private static final String fileSeparator = System.getProperty("file.separator");
	
	private Control control;
	
	private FloappFile file;
	
	private UploadedFile upFile;
	
	private List<FloappFile> fileList;
		
	public FileBean(){
		setControl( new Control( new HibernateDAOFactory() ) );
		setFile( new FloappFile() );
		setFileList(new ArrayList<FloappFile>());
	}
	
	public String download(){	
		
		return "OK";
	}
	
	public String upload() {
		try {
			String str = getUpFile().getName();
			String[] fileName = str.split(fileSeparator+fileSeparator);
			str = fileName[fileName.length-1];
			this.file.setFileName(str); 
			this.file = new FloappFile(getUpFile(),str);
			getControl().insertFile(file);
			return OK;
		} catch (FloAppException ioe) {
			System.out.println("File Upload Unsuccessful.");
			return FAILED;
		}

	}

	public UploadedFile getUpFile() {
		return this.upFile;
	}

	public void setUpFile(UploadedFile upFile) {
		this.upFile = upFile;
	}
	
	public Control getControl() {
		return control;
	}

	public void setControl(Control control) {
		this.control = control;
	}

	public FloappFile getFile() {
		return file;
	}

	public void setFile(FloappFile file) {
		this.file = file;
	}

	public List<FloappFile> getFileList() {
		setFileList(getControl().listFiles());
		return fileList;
	}

	public void setFileList(List<FloappFile> fileList) {
		this.fileList = fileList;
	}
	
	
}
